package com.itheima.restkeeper.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.BrandFace;
import com.itheima.restkeeper.basic.ResponseWrap;
import com.itheima.restkeeper.enums.BrandEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.BrandVo;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import com.itheima.restkeeper.utils.ResponseWrapBuild;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName BrandController.java
 * @Description 品牌Controller
 */
@RestController
@RequestMapping("brand")
@Slf4j
@Api(tags = "品牌controller")
public class BrandController {

    @DubboReference(version = "${dubbo.application.version}",check = false)
    BrandFace brandFace;

    @DubboReference(version = "${dubbo.application.version}",check = false)
    AffixFace affixFace;

    /**
     * @Description 品牌列表
     * @param brandVo 查询条件
     * @return
     */
    @PostMapping("page/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询品牌分页",notes = "查询品牌分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "brandVo",value = "品牌查询对象",required = true,dataType = "BrandVo"),
        @ApiImplicitParam(paramType = "path",name = "pageNum",value = "页码",dataType = "Integer"),
        @ApiImplicitParam(paramType = "path",name = "pageSize",value = "每页条数",dataType = "Integer")
    })
    public ResponseWrap<Page<BrandVo>> findBrandVoPage(
            @RequestBody BrandVo brandVo,
            @PathVariable("pageNum") int pageNum,
            @PathVariable("pageSize") int pageSize) throws ProjectException {
        try {
            //查询分页
            Page<BrandVo> brandVoPage = brandFace.findBrandVoPage(brandVo, pageNum, pageSize);
            //如果结果不为空，则为分页指定附件信息
            if (!EmptyUtil.isNullOrEmpty(brandVoPage)) {
                List<BrandVo> records = brandVoPage.getRecords();
                records.forEach(bVo->{
                    //一个品牌只会有一个logo，之所以会存成list是为了保存品牌之前可能存在的logo
                    AffixVo affixVo = affixFace.findAffixVoByBusinessId(bVo.getId()).get(0);
                    if (!EmptyUtil.isNullOrEmpty(affixVo)) {
                        bVo.setAffixVo(affixVo);
                    }
                });
                brandVoPage.setRecords(records);
            }
                //循环处理结果集
            //返回分页结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,brandVoPage);
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }

    /**
     * @Description 查询品牌下拉框
     * @return
     */
    @GetMapping("list")
    @ApiOperation(value = "查询品牌下拉框",notes = "查询品牌下拉框")
    public ResponseWrap<List<BrandVo>> findBrandVoList() throws ProjectException {
        try {
            //查询下拉框
            List<BrandVo> brandVoList = brandFace.findBrandVoList();
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,brandVoList);
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }

    /**
     * @Description 添加品牌
     * @param brandVo 对象信息
     * @return
     */
    @PostMapping
    @ApiOperation(value = "添加品牌",notes = "添加品牌")
    @ApiImplicitParam(name = "brandVo",value = "品牌对象",required = true,dataType = "BrandVo")
    ResponseWrap<BrandVo> createBrand(@RequestBody BrandVo brandVo) throws ProjectException {
        try {
            //添加品牌
            BrandVo brandv = brandFace.createBrand(brandVo);
            //绑定附件
            AffixVo affixVo = affixFace.bindBusinessId(AffixVo
                    .builder()
                    //业务id使用添加品牌时生成的id
                    .businessId(brandv.getId())
                    //附件id则使用添加附件时生成的id
                    .id(brandVo.getAffixVo().getId())
                    .build());
            //指定附件信息
            brandv.setAffixVo(affixVo);
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,brandv);
        } catch (Exception e) {
            log.error("保存品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.CREATE_FAIL);
        }
    }

    /**
     * @Description 修改品牌
     * @param brandVo 对象信息
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "修改品牌",notes = "修改品牌")
    @ApiImplicitParam(name = "brandVo",value = "品牌对象",required = true,dataType = "BrandVo")
    ResponseWrap<Boolean> updateBrand(@RequestBody BrandVo brandVo) throws ProjectException {
        try {
            //按ID修改品牌信息
            Boolean aBoolean = brandFace.updateBrand(brandVo);
            //修改成功后，处理附件图片信息
            if (aBoolean) {
                //先删除品牌在附件库中原来存在的附件
                Boolean aBoolean1 = affixFace.deleteAffixVoByBusinessId(brandVo.getId());
                //添加新的的附件
                affixFace.bindBusinessId(brandVo.getAffixVo());
            }
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,aBoolean);
        } catch (Exception e) {
            log.error("保存品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_FAIL);
        }
    }

    /**
     * @Description 删除品牌
     * @param brandVo 查询对象
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "删除品牌",notes = "删除品牌")
    @ApiImplicitParam(name = "brandVo",value = "品牌查询对象",required = true,dataType = "BrandVo")
    ResponseWrap<Boolean> deleteBrand(@RequestBody BrandVo brandVo ) throws ProjectException {
        try {
            //删除选中节点
            Boolean bBoolean = brandFace.deleteBrand(brandVo.getCheckedIds());
            //删除图片
            Boolean aBoolean = affixFace.deleteAffix(brandVo.getCheckedIds());
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,bBoolean&&aBoolean);
        } catch (Exception e) {
            log.error("删除品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.DELETE_FAIL);
        }
    }

    /**
     * @Description 查找品牌
     * @param brandId 品牌ID
     * @return
     */
    @GetMapping("{brandId}")
    @ApiOperation(value = "查找品牌",notes = "查找品牌")
    @ApiImplicitParam(paramType = "path",name = "brandId",value = "品牌Id",dataType = "Long")
    ResponseWrap<BrandVo> findBrandByBrandId(@PathVariable("brandId") Long brandId) throws ProjectException {
        //品牌是否为空判断
        try {
            //根据ID查询品牌信息
            BrandVo brandByBrandId = brandFace.findBrandByBrandId(brandId);
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,brandByBrandId);
        } catch (Exception e) {
            log.error("查找品牌所有品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.SELECT_BRAND_FAIL);
        }
    }

    @PostMapping("update-brand-enableFlag")
    @ApiOperation(value = "修改品牌状态",notes = "修改品牌状态")
    @ApiImplicitParam(name = "brandVo",value = "品牌查询对象",required = true,dataType = "BrandVo")
    ResponseWrap<Boolean> updateBrandEnableFlag(@RequestBody BrandVo brandVo) throws ProjectException {
        try {
            //修改品牌状态
            Boolean aBoolean = brandFace.updateBrand(brandVo);
            //返回结果
            return ResponseWrapBuild.build(BrandEnum.SUCCEED,aBoolean);
        } catch (Exception e) {
            log.error("修改品牌状态：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_FAIL);
        }
    }

}
